#-*- coding.utf-8 -*-
import os,chardet,re

#------判断文本编码 begin------#
def detect_encoding(text):
    result = chardet.detect(text)
    encoding = result['encoding']
    confidence = result['confidence']
    return encoding, confidence
def getTxtCharset(filename:str):
    with open(filename, 'rb') as f:
        text = f.read()
    encoding, confidence = detect_encoding(text)
    return encoding
    #print(f"Detected encoding: {encoding}")
    #print(f"Confidence: {confidence}")
#------判断文本编码 end ------#
OUTPUT_CHARSET = 'utf-8'

lrc_timestamps_pattern = '\[(\d{2}:)?\d{2}:\d{2}\.\d{2}\]'
srt_timestamps_pattern = '\d{2}:\d{2}:\d{2},\d{3}'

def loadcontent(path:str):
    with open(path,'r',encoding=getTxtCharset(path)) as input:
        lines = input.readlines()
    timestamps_content_dict = {}
    if path.endswith('.lrc'): # 字典结构 {时间戳:[第一行字幕,第二行字幕,...]}
        for line in lines:
            lts = re.match(lrc_timestamps_pattern,line)
            if lts:
                ts = lts.group(0) # lrc时间戳
                #timestamps.append(convertLrcSrtTimestamps(ts)) # 转换成srt的时间戳
                to_srt_ts = convertLrcSrtTimestamps(ts) # 转换成srt的时间戳
                # 字幕内容
                if not timestamps_content_dict.get(to_srt_ts):
                    timestamps_content_dict[to_srt_ts] = [lts.string[lts.span()[1]:]]
                else:
                    timestamps_content_dict[to_srt_ts].append(lts.string[lts.span()[1]:])
    elif path.endswith('.srt'): # 字典结构 {字幕出现时间点:{字幕消失时间点:[第一行字幕,第二行字幕,...]}}
        for index in range(len(lines)):
            if re.match('^\n|^\r|\^\n\r|^\r\n',lines[index]):
                continue
            sts = re.findall(srt_timestamps_pattern,lines[index])
            if len(sts) == 2:
                start_timestamps = convertLrcSrtTimestamps(sts[0])
                end_timestamps = convertLrcSrtTimestamps(sts[1])
                if not timestamps_content_dict.get(start_timestamps):
                    timestamps_content_dict[start_timestamps] = {end_timestamps:[]}
                else:
                    print(f'srt字幕{sts[0]}时间点重复，请检测字幕文件校对时间！')
                if re.match('^\n|^\r|\^\n\r|^\r\n',lines[index+2]):
                    timestamps_content_dict[start_timestamps][end_timestamps].append(lines[index+1])
                else:# 双语srt字幕会多一行
                    timestamps_content_dict[start_timestamps][end_timestamps].append(lines[index+1].strip('\n'))
                    timestamps_content_dict[start_timestamps][end_timestamps].append(lines[index+2])
    return timestamps_content_dict

def convertLrcVsSrt(data:dict,to_path_file:str):
    with open(to_path_file,'w',encoding=OUTPUT_CHARSET) as w:
        if to_path_file.endswith('.srt'):
            dict_keys = list(data.keys())
            #print(dict_keys)
            keys_sum = len(dict_keys)
            for index in range(keys_sum-1):
                #print(index+1)
                w.write(str(index+1)+'\n')
                #print(f'{dict_keys[index]} --> {dict_keys[index+1]}')
                w.write(f'{dict_keys[index]} --> {dict_keys[index+1]}\n')
                contents = data[dict_keys[index]]
                for c in contents:
                    #print(c)
                    w.write(c)
                w.write('\n')
            # 最后一句需要单独处理时间戳
            #print(keys_sum)
            w.write(str(keys_sum)+'\n')
            #print(f'{dict_keys[keys_sum-1]} --> ')
            w.write(f'{dict_keys[keys_sum-1]} --> \n')
            contents = data[dict_keys[keys_sum-1]] 
            for c in contents:
                #print(c)
                w.write(c)
        elif to_path_file.endswith('.lrc'):
            for ts,va in data.items():
                #print(ts,va)
                for vas,vac in va.items():
                    for c in vac:
                        #print(ts,vas,c)
                        w.write(f'[{ts}]{c}\n')

# 若目录不存在 创建
def validDir(_dir:str):
    if not os.path.exists(_dir):
        os.makedirs(_dir)
    return _dir

# lrc与srt时间戳相互转换 限时长小于60分钟的'_'
def convertTimestamps(timestamps:str):
    if '[' in timestamps: # lrc>srt timestamps
        timestamps = timestamps.replace('[','').replace(']','')
        ts_clip = timestamps.split(':')
        ts_clip.reverse() # 反转时间戳 从秒开始处理
        to_srt_ts = []
        if len(ts_clip) == 2:
            ts_clip.append('00')
        for ts in ts_clip:
            to_srt_ts.insert(0,ts)
        return ':'.join(to_srt_ts).replace('.',',')+'0'
    else: # srt>lrc timestamps
        timestamps = timestamps.replace(' ','').replace('\n','')[:-1]
        ts_clip = timestamps.split(':')
        ts_clip.reverse() # 反转时间戳 从秒开始处理
        to_srt_ts = []
        for ts in ts_clip:
            to_srt_ts.insert(0,ts)
        return ':'.join(to_srt_ts).replace(',','.')

# lrc与srt时间戳相互转换 时长不限^_^
def convertLrcSrtTimestamps(timestamps:str):
    if '[' in timestamps: # lrc>srt timestamps
        timestamps = timestamps.replace('[','').replace(']','')
        ts_clip = timestamps.split(':')
        if len(ts_clip) == 2:
            hh = '{:0>2d}'.format(int(ts_clip[0])//60)
            mm = '{:0>2d}'.format(int(ts_clip[0])%60)
            ss = ts_clip[1].replace('.',',')
        return f'{hh}:{mm}:{ss}'
    else: # srt>lrc timestamps
        timestamps = timestamps.replace(' ','').replace('\n','')
        ts_clip = timestamps.split(':')
        if len(ts_clip) == 3:
            hh_to_mm = int(ts_clip[0])*60 + int(ts_clip[1])
            return '{:0>2d}'.format(hh_to_mm)+':'+ts_clip[2].replace(',','.')

def load(path:str):
    if path.endswith("lrc"):
        hh_list = []
        mm_list = []
        ss_list = []
        mms_list = []
        content_list = []
        file = open(path,"r",encoding=getTxtCharset(path))
        sub = file.readlines()
        sub[0]=sub[0][1:len(sub[0])+1]
        file.close()
        for n in sub:
            n = n.strip(" ")
            n = n.strip("[")
            content = n.split("]")[1]
            time = n.split("]")[0]
            hh_list.append(str(int(time.split(':')[0])//60).rjust(2,'0'))
            mm_list.append(str(int(time.split(':')[0])%60).rjust(2,'0'))
            ss_list.append(str(time.split(':')[1].split('.')[0]).rjust(2,'0'))
            mms_list.append(str(time.split(':')[1].split('.')[1]).ljust(3,'0'))
            content_list.append(content)
        finallist = [hh_list,mm_list,ss_list,mms_list,content_list]
        return(finallist)
    
    if path.endswith("srt"):
        hh_list = []
        mm_list = []
        ss_list = []
        mms_list = []
        content_list = []
        content2_list = [] #双语字幕会多一行
        file = open(path,"r",encoding=getTxtCharset(path))
        sub = file.readlines()
        sub[0]=str(0)
        file.close()
        a= 0
        for n in sub:
            n=n.strip('\n')
            if n.isdecimal() and ' --> ' in sub[int(a)+1] :
                time = sub[int(a)+1].split(' --> ')[0]
                hh = str((time.split(':')[0]))
                mm = str((time.split(':')[1]))
                ss = str(time.split(',')[0].split(':')[2])
                mms =  str(time.split(',')[1])
                content = sub[a+2]
                content2 = sub[a+3] #双语字幕会多一行
                hh_list.append(hh)
                mm_list.append(mm)
                ss_list.append(ss)
                mms_list.append(mms)
                content_list.append(content)
                content2_list.append(content2) #双语字幕会多一行
            a += 1
    finallist = [hh_list,mm_list,ss_list,mms_list,content2_list]
    return(finallist)


def convert(data,path):
    if path.endswith("txt"):
        content_list = data[4]
        file = open(path,"w",encoding=OUTPUT_CHARSET)
        for a in content_list:
            file.write(a)
        file.close()
     
    if path.endswith("lrc"):
        hh_list = data[0]
        mm_list = data[1]
        ss_list = data[2]
        mms_list = data[3]
        content_list = data[4]
        file = open(path,"w",encoding=OUTPUT_CHARSET)
        for a in range(len(mm_list)):
            file.write('['+mm_list[a]+':'+ss_list[a]+'.'+mms_list[a]+']'+content_list[a])
        file.close()
            
    if path.endswith("srt"):
        hh_list = data[0]
        mm_list = data[1]
        ss_list = data[2]
        mms_list = data[3]
        content_list = data[4]
        file = open(path,"w",encoding=OUTPUT_CHARSET)
        hh_list.append(hh_list[len(hh_list)-1])
        mm_list.append(mm_list[len(mm_list)-1])
        ss_list.append(int(ss_list[len(ss_list)-1])+5)
        mms_list.append(mms_list[len(mms_list)-1])
        for a in range(len(hh_list)-1):
            file.write(str(a)+'\n')
            file.write(str(hh_list[a])+':'+str(mm_list[a])+':'+str(ss_list[a])+','
                       +str(mms_list[a])+" --> "+str(hh_list[a+1])+':'+str(mm_list[a+1])
                       +':'+str(ss_list[a+1])+','+str(mms_list[a+1])+'\n')
            file.write(content_list[a]+'\n')
        file.close()

if __name__ == '__main__' :
    data = loadcontent(r'C:/KwDownload/song/ZARD-DAN DAN 心魅かれてく.lrc')
    convertLrcVsSrt(data, r'C:/KwDownload/song/ZARD-DAN DAN 心魅かれてく.srt')
